import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {Storage} from "@ionic/storage";

@Injectable()
export class LocalStorageService {
    /**
     * 构造函数
     * @param {Storage} storage
     */
    constructor(private storage: Storage) {
    }

    /**
     * 设置数据
     * @param {string} key
     * @param value
     * @returns {Observable<any>}
     */
    setData(key: string, value: any): Observable<any> {
        return Observable.create(observer => {
            this.storage.set(key, value).then(result => {
                observer.next(result);
                observer.complete();
            }).catch(error => {
                observer.error(error);
            });
        });
    }

    /**
     * 获取数据
     * @param key
     * @returns {Observable<any>}
     */
    getData(key: string): Observable<any> {
        return Observable.create(observer => {
            this.storage.get(key).then(result => {
                observer.next(result);
                observer.complete();
            }).catch(error => {
                observer.error(error);
            });
        });
    }

    /**
     * 删除数据
     * @param key
     * @returns {Observable<any>}
     */
    deleteData(key: string): Observable<any> {
        return Observable.create(observer => {
            this.storage.remove(key).then(result => {
                observer.next(result);
                observer.complete();
            }).catch(error => {
                observer.error(error);
            });
        });
    }

    /**
     * 获取存储数量
     * @returns {Observable<any>}
     */
    getLength(): Observable<number> {
        return Observable.create(observer => {
            this.storage.length().then(result => {
                observer.next(result);
                observer.complete();
            }).catch(error => {
                observer.error(error);
            });
        });
    }

    /**
     * 获取所有键
     * @returns {Observable<any>}
     */
    getKeys(): Observable<string[]> {
        return Observable.create(observer => {
            this.storage.keys().then(result => {
                observer.next(result);
                observer.complete();
            }).catch(error => {
                observer.error(error);
            });
        });
    }

    /**
     * 遍历数据
     * @param {(value: any, key: string, iterationNumber: Number) => any} callback
     * @returns {Observable<void>}
     */
    forEach(callback: (value: any, key: string, iterationNumber: Number) => any): Observable<void> {
        return Observable.create(observer => {
            this.storage.forEach(callback).then(() => {
                observer.next();
                observer.complete();
            }).catch(error => {
                observer.error(error);
            });
        });
    }

    clear() {
        let o = this.storage.clear()
            .then((res) => {
                return res;
            });
        return o;
    }
}
